package com.rongke.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.FailException;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FlowTypeEnum;
import com.rongke.enums.MsgTypeEnum;
import com.rongke.enums.PayTypeEnum;
import com.rongke.enums.UserTypeEnum;
import com.rongke.model.*;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import com.rongke.sms.SmsUtil;
import com.rongke.utils.*;
import com.rongke.web.config.ConfigUtil;
import com.rongke.wxPayUtil.PayUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @version : Ver 1.0
 * @MuserController
 * @Controller
 */
@RestController
@RequestMapping(value = "/api/muser")
@Transactional
@CrossOrigin(origins = "*", maxAge = 3600)
public class MuserController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private MuserService muserService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CouponUserService couponUserService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private MachineService machineService;
    @Autowired
    private AdminService adminService;
    @Autowired
    public ConfigUtil config;
    @Autowired
    public CacheUtil cacheUtil;
    @Autowired
    public FlowDetailService flowDetailService;
    @Autowired
    private MsgUserService msgUserService;
    @Autowired
    private SystemParmService systemParmService;
    @Autowired
    private MessageService messageService;
    @Autowired
    public SmsUtil smsUtil;
    private static final String NAME = "FJB";
    private static final String PWD = "fjb123456";
    private static final String URL = "http://yl.mobsms.net/send/gsend.aspx";
    private static String DISC_URL = "/home/indexData/data";
    public static String alinotify = "/api/money/alipay/registerSucc";
    public static String wxnotify = "/api/money/wxpay/registerSucc";


    /**
     * @return 返回值JsonResp
     * @发送验证码
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    public JsonResp sendCode(String phone) throws Exception {

        log.debug("发送验证码");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        Muser findUser = muserService.selectOne(ew);
        if (findUser != null) {
            if (findUser.getUserName() == null && findUser.getSource() != null) {
                return JsonResp.ok(findUser.getId());
            } else {
                return JsonResp.toFail("已经注册过的人不能重复注册");
            }
        } else {
            Boolean sendCode = smsUtil.sendCode(phone);
            if (sendCode) {
                return JsonResp.ok("获取验证码成功");
            } else {
                return JsonResp.fa("获取验证码失败！");
            }
        }
    }

    /**
     * @return 返回值JsonResp
     * @发送验证码
     */
    @RequestMapping(value = "/getCode", method = RequestMethod.GET)
    public JsonResp getCode(String phone) throws Exception {

        log.debug("发送验证码");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        Boolean sendCode = smsUtil.sendCode(phone);
        if (sendCode) {
            return JsonResp.ok("获取验证码成功");
        } else {
            return JsonResp.fa("获取验证码失败！");
        }
    }


    /**
     * @param muser
     * @return 返回值JsonResp
     * @注册
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JsonResp addMuser(@RequestBody Muser muser, HttpServletRequest request) {
        log.debug("注册");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", muser.getPhone());
        Muser muser1 = muserService.selectOne(ew);
        String code = request.getParameter("code");
        String recommendId = request.getParameter("recommendId");
        if (StringUtil.isEmpty(code)) {
            return JsonResp.fa("请输入验证码");
        }
        Boolean flag = smsUtil.checkCode(muser.getPhone(), code);
        if (!flag) {
            return JsonResp.fa("验证码错误");
        }
        if (muser1 != null && muser1.getmStatus() != 3) {
            return JsonResp.fa("该手机号已经注册");
        }
        muser.setPassword(Md5.md5Encode(muser.getPassword()));
        muser.setUserType(1);
        muser.setMemberLevel(1);
        muser.setGmtDatetime(new Date());
        if (muser1 != null && muser1.getmStatus() == 3) {
            muser.setId(muser1.getId());
            muser.setRecommendUserIds(muser1.getRecommendUserIds());
            muser.setmStatus(3);
            muserService.updateById(muser);
        } else {
            muserService.insert(muser);
        }
        Address address = muser.getAddress();

        address.setProvince(AddressController.convertProvince(address.getProvince()));//转化处理带"省"、"市"、"自治区"

        address.setTag("0");
        address.setMuserId(muser.getId());
        addressService.insert(address);
        Long id = muser.getId();
        String link = "https://wx.miduu.com/1.6.0zhuce_tiyan.html?id=" + id;
        String url = RequestUtils.getHostPath(request);
        String path = PubLib.getFileDir(request) + File.separator + UUID.randomUUID() + ".png";
        File saveFile = new File(path);
        String logoPath = PubLib.getFileDir(request) + File.separator + "android-template.png";
        try {
            QRCodeUtil2.encode(link, 600, 600, logoPath, path);
        } catch (Exception e) {
            return JsonResp.fa("个人二维码生成失败");
        }
        String qrCode = url + "/" + saveFile.getParentFile().getName() + "/" + saveFile.getName();
        muser.setQrCode(qrCode);
        if (StringUtil.isNotEmpty(recommendId)) {
            Muser recomendUser = muserService.selectById(recommendId);
            String recommendIds = StringUtil.isEmpty(recomendUser.getRecommendUserIds()) == true ? recommendId : recommendId + "," + recomendUser.getRecommendUserIds();
            muser.setRecommendUserIds(recommendIds);
            Muser recomendMuser = muserService.selectById(recommendId);
            if (recomendMuser.getmStatus() == 2)
                return JsonResp.fa("推荐人账号已被禁用，注册失败");
            //将其推荐人姓名放入缓存
            cacheUtil.put("recomendUser" + muser.getId(), recomendMuser.getUserName());
        }
        muser.setmStatus(1);
        muserService.updateById(muser);
        //创建账户
        Account account = new Account();
        account.setMuserId(muser.getId());
        account.setFrozen(false);
        accountService.insert(account);
        //赠送优惠券
        releaseRegisterCoupon(id);

        return JsonResp.ok(muser);
    }


    /**
     * @param userId 用户id
     * @param type   支付方式
     * @return 返回值JsonResp
     * @彩虹会员支付
     */
    @RequestMapping(value = "/caiHongPay", method = RequestMethod.GET)
    public JsonResp caiHongPay(Long userId, Integer type, HttpServletRequest request) {
        log.debug("彩虹会员支付");
        //如果注册彩虹会员  支付
        EntityWrapper<SystemParm> ew1=new EntityWrapper<>();
        ew1.setSqlSelect("rainbow_price");
        BigDecimal rainbowPrice= (BigDecimal) systemParmService.selectObj(ew1);
        if(null==rainbowPrice)
            return JsonResp.toFail("暂未配置彩虹会员价格");
//        BigDecimal money = new BigDecimal(299);
        BigDecimal money = rainbowPrice;
        Muser muser = muserService.selectById(userId);
        if (muser.getMemberType() == 2) {
            return JsonResp.fa("您已注册彩虹会员");
        }
        EntityWrapper<Account> ew = new EntityWrapper<>();
        ew.eq("muser_id", userId);
        Account account = accountService.selectOne(ew);
        if (type == PayTypeEnum.DUOBI.getType()) {
            if (account.getDuoBi().compareTo(money) < 0) {
                return JsonResp.fa("账户余额不足");
            } else {
                account.setDuoBi(account.getDuoBi().subtract(money));
            }
            muser.setMemberType(2);
            FlowDetail duoBi = new FlowDetail();
            duoBi.setMoney(money);
            duoBi.setFlowType(FlowTypeEnum.ORDER.getType());
            duoBi.setMuserId(userId);
            duoBi.setTitle("注册彩虹会员哆币支付");
            flowDetailService.insert(duoBi);

        } else if (type == PayTypeEnum.YABI.getType()) {
            money = new BigDecimal(0.1);
            if (account.getYaBi().compareTo(money) < 0) {
                return JsonResp.fa("账户余额不足");
            } else {
                account.setYaBi(account.getYaBi().subtract(money));
            }
            muser.setMemberType(2);
            FlowDetail yaBi = new FlowDetail();
            yaBi.setMoney(money);
            yaBi.setFlowType(FlowTypeEnum.ORDER.getType());
            yaBi.setMuserId(userId);
            yaBi.setTitle("注册彩虹会员哆雅币支付");
            flowDetailService.insert(yaBi);
        } else if (type == PayTypeEnum.ZHIFUBAO.getType()) {
            String sym = request.getRequestURL().toString().split("/api/")[0].replace("http", "https");
            String trade_no = (userId + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0, 32);
            String stringStringMap = null;
            try {
                stringStringMap = PayUtils.AliPay(trade_no, money.doubleValue(), "支付宝支付", "支付宝支付—", sym + alinotify);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (StringUtil.isNotEmpty(stringStringMap)) {
                return JsonResp.ok("成功", stringStringMap);
            } else {
                log.debug("支付宝支付失败");
                throw new FailException();
            }
        } else if (type == PayTypeEnum.WEIXIN.getType()) {
            String sym = request.getRequestURL().toString().split("/api/")[0].replace("http", "https");
            String trade_no = (userId + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0, 32);
            Map map;
            map = PayUtils.WxPay(trade_no, money.doubleValue(), "微信支付", sym + wxnotify);
            log.debug("新建訂單。。。。微信支付map=" + map);
            if (!map.isEmpty()) {
                return JsonResp.ok("成功", map);
            } else {
                log.debug("微信支付失败");
                throw new FailException();
            }
        }
        account.setYaBi(account.getYaBi().add(new BigDecimal(99)));//升级彩虹送雅币
        muserService.updateById(muser);
        accountService.updateById(account);
        return JsonResp.ok();
    }


    /**
     * @param phone    用户名
     * @param password 密码
     * @return 返回值JsonResp
     * @(前台)登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResp login(String phone, String password) {
        log.debug("(前台)登录");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        String str[] = {"1", "3"};
        ew.in("m_status", str);//账号状态1代表正常2代表封号3异地系统注册
        Muser muser = muserService.selectOne(ew);
        if (muser == null) {
            return JsonResp.fa("账号错误或者已被禁用！");
        }
        if (StringUtil.isEmpty(password) || !Md5.md5Encode(password).equals(muser.getPassword())) {
            return JsonResp.fa("密码错误！");
        }
        String token = null;
        if (cacheUtil.hasKey(String.valueOf(muser.getId()))) {
            token = cacheUtil.get(String.valueOf(muser.getId()));
            cacheUtil.delkey(String.valueOf(muser.getId()));
            cacheUtil.delkey(token);
        }
        //生成一个新的token;
        token = Md5.md5Encode(phone + new Date().getTime());
        cacheUtil.set(String.valueOf(muser.getId()), token, 30 * 24 * 60 * 60);
        cacheUtil.set(token, String.valueOf(muser.getId()), 30 * 24 * 60 * 60);
        muser.setToken(token);
        muserService.updateById(muser);
        return JsonResp.ok(muser);

    }


    /**
     * @param muserOrAddress
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateMuser(@RequestBody MuserOrAddress muserOrAddress) {
        log.debug("修改 姓名 性别 生日 地址");
        Muser muser = new Muser();
        muser.setId(muserOrAddress.getMuserId());
        if (null != muserOrAddress.getBirthday() || null != muserOrAddress.getUserName() || null != muserOrAddress.getSex()) {
            muser.setBirthday(muserOrAddress.getBirthday());
            muser.setUserName(muserOrAddress.getUserName());
            muser.setSex(muserOrAddress.getSex());
            muserService.updateById(muser);
        }
        EntityWrapper<Address> ew = new EntityWrapper<>();
        ew.eq("muser_id", muserOrAddress.getMuserId());
        ew.eq("tag", "0");
        Address address = addressService.selectOne(ew);
        if (address == null) {
            address = new Address();
            address.setProvince(muserOrAddress.getProvince());
            address.setCity(muserOrAddress.getCity());
            address.setArea(muserOrAddress.getArea());
            address.setMuserId(muserOrAddress.getMuserId());
            address.setName(muser.getUserName());
            address.setPhone(muser.getPhone());
            address.setTag("0");
            addressService.insert(address);
        } else {
            address.setProvince(muserOrAddress.getProvince());
            address.setCity(muserOrAddress.getCity());
            address.setArea(muserOrAddress.getArea());
            addressService.updateById(address);
        }
        return JsonResp.ok(muserOrAddress);
    }

    /**
     * 更新会员信息
     *
     * @param muser
     * @return
     */
    @RequestMapping(value = "/uptMuser", method = RequestMethod.POST)
    public JsonResp uptMuser(@RequestBody Muser muser) {
        log.debug("更新会员信息");
        if (null == muser.getId())
            return JsonResp.toFail("用户id不能为空");
        muserService.updateById(muser);
        return JsonResp.ok();
    }

    /**
     * @param oldPassword 旧密码
     *                    newPassword  新密码
     * @return 返回值JsonResp
     * @修改密码
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.GET)
    public JsonResp updatePassword(String token, String oldPassword, String newPassword) {
        log.debug("修改密码");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        oldPassword = Md5.md5Encode(oldPassword);
        Long userId = Long.valueOf(cacheUtil.get(token));
        Muser muser = muserService.selectById(userId);
        if (!oldPassword.equals(muser.getPassword())) {
            return JsonResp.fa("密码错误");
        }
        newPassword = Md5.md5Encode(newPassword);
        muser.setPassword(newPassword);
        muserService.updateById(muser);
        return JsonResp.ok(muser);
    }

    /**
     * 已用其他方式注册账号的人修改密码、添加其他注册动作（如发放优惠券等）
     *
     * @param muser
     * @return
     */
    @RequestMapping(value = "/uptRegisteredPassword", method = RequestMethod.POST)
    public JsonResp uptRegisteredPassword(@RequestBody Muser muser, HttpServletRequest request) {
        log.debug("已用其他方式注册账号的人修改密码、添加其他注册动作（如发放优惠券等）");
        muser.setPassword(Md5.md5Encode(muser.getPassword()));
        if (null == muser.getId()) {
            JsonResp.ok("用户id为空");
        }
        Long id = muser.getId();
        Muser muser1 = muserService.selectById(id);
        String link = "https://wx.miduu.com/1.6.0zhuce_tiyan.html?id=" + id;
        String url = RequestUtils.getHostPath(request);
        String path = PubLib.getFileDir(request) + File.separator + UUID.randomUUID() + ".png";
        File saveFile = new File(path);
        String logoPath = PubLib.getFileDir(request) + File.separator + "android-template.png";
        try {
            QRCodeUtil2.encode(link, 600, 600, logoPath, path);
        } catch (Exception e) {
            return JsonResp.fa("个人二维码生成失败");
        }
        String qrCode = url + "/" + saveFile.getParentFile().getName() + "/" + saveFile.getName();
        muser.setQrCode(qrCode);
        String recommendIds = muser1.getRecommendUserIds();
        if (StringUtil.isNotEmpty(recommendIds)) {
            Long recomendId = Long.valueOf(recommendIds.split(",")[0]);
            Muser recomendMuser = muserService.selectById(recomendId);
            if (recomendMuser.getmStatus() == 2)
                return JsonResp.fa("推荐人账号已被禁用，注册失败");
            //将其推荐人姓名放入缓存
            cacheUtil.put("recomendUser" + muser.getId(), recomendMuser.getUserName());
        }
        //赠送优惠券
        releaseRegisterCoupon(id);
        muser.setGmtDatetime(new Date());
        muserService.updateById(muser);
        return JsonResp.ok(muser);
    }

    /**
     * @param oldPhone 久电话
     *                 code  验证码
     * @return 返回值JsonResp
     * @修改密码
     */
    @RequestMapping(value = "/checkOldPhone", method = RequestMethod.GET)
    public JsonResp checkOldPhone(String token, String oldPhone, String code) {
        log.debug("修改密码");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Boolean flag = smsUtil.checkCode(oldPhone, code);
        if (!flag) {
            return JsonResp.fa("验证码错误");
        }
        Long userId = Long.valueOf(cacheUtil.get(token));
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("id", userId);
        ew.eq("phone", oldPhone);
        Muser muser = muserService.selectOne(ew);
        if (muser == null) {
            return JsonResp.fa("手机号不存在");
        }
        return JsonResp.ok("", "200");
    }

    /**
     * @更换头像 avatarUtl 头像
     */
    @RequestMapping(value = "/changeAvatarUrl", method = RequestMethod.GET)
    public JsonResp changeAvatarUrl(HttpServletRequest request) {
        log.debug("更换头像");
        String token = request.getParameter("token");
        String avatarUtl = request.getParameter("avatarUtl");
        System.out.print("头像地址：" + avatarUtl);
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        if (StringUtil.isEmpty(avatarUtl)) {
            return JsonResp.fa("头像为空");
        }
        Long userId = Long.valueOf(cacheUtil.get(token));
        Muser muser = muserService.selectById(userId);
        muser.setAvatarUrl(avatarUtl);
        //更新二维码
        Long id = muser.getId();
        File logeFile = new File(avatarUtl);
        String logoPath = PubLib.getFileDir(request) + File.separator + logeFile.getParentFile().getName() + File.separator + logeFile.getName();
        String link = "https://wx.miduu.com/1.6.0zhuce_tiyan.html?id=" + id;
        String url = RequestUtils.getHostPath(request);
        String path = PubLib.getFileDir(request) + File.separator + UUID.randomUUID() + ".png";
        File saveFile = new File(path);
        try {
            QRCodeUtil2.encode(link, 600, 600, logoPath, path);
        } catch (Exception e) {
            return JsonResp.fa("个人二维码生成失败");
        }
        String qrCode = url + "/" + saveFile.getParentFile().getName() + "/" + saveFile.getName();
        muser.setQrCode(qrCode);
        muserService.updateById(muser);
        return JsonResp.ok();
    }


    /**
     * 忘记密码
     *
     * @return 返回值JsonResp
     * @发送验证码
     */
    @RequestMapping(value = "/lostPassword", method = RequestMethod.GET)
    public JsonResp lostPassword(String phone, String code, String password) throws Exception {
        log.debug("忘记密码");
        Boolean flag = smsUtil.checkCode(phone, code);
        if (!flag) {
            return JsonResp.fa("验证码错误");
        }
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        Muser findUser = muserService.selectOne(ew);
        if (findUser == null) {
            return JsonResp.toFail("该用户不存在");
        } else {
            findUser.setPassword(Md5.md5Encode(password));
            muserService.updateById(findUser);
        }
        return JsonResp.ok();
    }


    /**
     * @param newPhone 旧电话
     *                 code  验证码
     * @return 返回值JsonResp
     * @修改密码
     */
    @RequestMapping(value = "/updatePhone", method = RequestMethod.GET)
    public JsonResp updatePhone(String token, String newPhone, String code) {
        log.debug("修改手机号码");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Boolean flag = smsUtil.checkCode(newPhone, code);
        if (!flag) {
            return JsonResp.fa("验证码错误");
        }
        Long userId = Long.valueOf(cacheUtil.get(token));
        Muser muser = muserService.selectById(userId);
        muser.setPhone(newPhone);
        muserService.updateById(muser);
        return JsonResp.ok("", "200");
    }


    /**
     * @param id 会员id
     *           profitability  提成比例
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/updatePb", method = RequestMethod.POST)
    public JsonResp updatePb(Long id, Double profitability) {
        log.debug("修改");
        Muser muser = muserService.selectById(id);
        muser.setProfitability(profitability);
        muserService.updateById(muser);
        return JsonResp.ok("", "200");
    }

    /**
     * 获取用户openid
     *
     * @param code 微信返回的code
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/getOpenid", method = RequestMethod.GET)
    public JsonResp getOpenid(String code) {
        log.debug("获取用户openid");
        String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx33ab5c735daf2be5&secret=40bc237094e931b99151e3efc3afe053&code=" + code + "&grant_type=authorization_code";
        String openId = "";
        try {
            URL getUrl = new URL(access_token_url);
            HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] b = new byte[size];
            is.read(b);
            String message = new String(b, "UTF-8");
            JSONObject json = JSONObject.parseObject(message);
            openId = json.getString("openid");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResp.ok(openId);
    }


    /**
     * @param id 用户id
     * @return 返回值JsonResp
     * @获取用户详情
     */
    @RequestMapping(value = "/findUserDetail", method = RequestMethod.GET)
    public JsonResp findUserDetail(Long id) {
        log.debug("获取用户详情");
        Account account = accountService.selectAccountAndUserMess(id);
        Muser muser = account.getMuser();
        String recommendUserIds = muser.getRecommendUserIds();
        if (StringUtil.isNotEmpty(recommendUserIds)) {
            Muser parsentUser = muserService.selectById(recommendUserIds.split(",")[0]);
            muser.setParsentUserName(parsentUser.getUserName());
        }
        EntityWrapper<Address> ew = new EntityWrapper<>();
        ew.eq("muser_id", id);
        ew.eq("tag", "0");
        Address address = addressService.selectOne(ew);
        Map map = new HashMap();
        map.put("account", account);
        map.put("address", address);
        return JsonResp.ok(map);
    }

    /**
     * @param phone 用户电话
     * @return 返回值JsonResp
     * @获取用户详情
     */
    @RequestMapping(value = "/checkPhone", method = RequestMethod.GET)
    public JsonResp checkPhone(String phone) {
        log.debug("检查用户是否已注册");
        if (StringUtil.isEmpty(phone)) {
            return JsonResp.fa("参数为空");
        }
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        Muser muser = muserService.selectOne(ew);
        Boolean flag = false;
        if (muser != null) {
            flag = true;
        } else {
            //发送验证码
            Boolean sendCode = smsUtil.sendCode(phone);
        }
        return JsonResp.ok(flag);
    }


    /**
     * @param machineCode 机器码
     *                    phone  会员手机号
     * @return 返回值JsonResp
     * @保存机器码
     */
    @RequestMapping(value = "/saveMachineCode/{parameter}", method = RequestMethod.GET)
    public JsonResp saveMachineCode(@PathVariable String parameter, String machineCode, String phone) {
        log.debug("保存机器码");
        String salt = "7r^st1_9se13u";
        String str = "machineCode=" + machineCode + "&phone=" + phone + salt;
        String resultString = Md5.md5Encode(str);

        if (!resultString.equals(parameter)) {
            return JsonResp.fa("请求出错");
        }
        EntityWrapper<Machine> ew = new EntityWrapper<>();
        ew.eq("machine_code", machineCode);
        Machine machine = machineService.selectOne(ew);
        Long userId = machine.getMuserId();
        //获取推荐人
        Muser recomendUser = muserService.selectById(userId);
        if (recomendUser == null) {
            return JsonResp.fa("该机器尚未绑定会员");
        }
        String ids = StringUtil.isEmpty(recomendUser.getRecommendUserIds()) == true ? recomendUser.getId() + "" : recomendUser.getId() + "," + recomendUser.getRecommendUserIds();
        Muser muser = new Muser();
        muser.setPhone(phone);
        muser.setRecommendUserIds(ids);
        muser.setPassword(Md5.md5Encode("123456"));
        muser.setmStatus(3);
        muser.setUserType(1);
        muser.setMemberType(1);
        muser.setSource(machineCode);
        muser.setMemberLevel(1);
        muserService.insert(muser);
        Account account = new Account();
        account.setMuserId(muser.getId());
        account.setFrozen(false);
        accountService.insert(account);

        return JsonResp.ok("保存成功");
    }


    /**
     * @param muser
     * @return 返回值JsonResp
     * @申请百夫长
     */
    @RequestMapping(value = "/applyCenturion", method = RequestMethod.POST)
    public JsonResp applyCenturion(@RequestBody Muser muser) {
        log.debug("申请百夫长");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("phone", muser.getPhone());
        Muser muser1 = muserService.selectOne(ew);
        if (muser1 == null) {
            return JsonResp.fa("此会员不存在");
        }
        muser1.setRealName(muser.getUserName());
        muser1.setIdCard(muser.getIdCard());
        muser1.setUserType(UserTypeEnum.APPLYCENTURION.getType());//申请百夫长状态
        muserService.updateById(muser1);
        return JsonResp.ok();
    }

    /**
     * @param id 用户id
     * @return 返回值JsonResp
     * @根据id查找个人资料
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectMuser(Long id) {
        if (id == -1) {
            return JsonResp.fa("参数错误");
        }
        log.debug("根据id查找个人资料");
        Address address = addressService.selectUserMessage(id);
        if (address == null) {
            return JsonResp.fa("未查到相关资料");
        }
        return JsonResp.ok(address);
    }

    /**
     * @param id 用户id
     * @return 返回值JsonResp
     * @会员中心
     */
    @RequestMapping(value = "/selectVipMessage", method = RequestMethod.GET)
    public JsonResp selectVipMessage(Long id) {
        log.debug("会员中心");
        Account account = accountService.selectAccountAndUserMess(id);
        if (account != null) {
            Muser muser = account.getMuser();
            int leveal = muser.getMemberLevel();
            String str = muserService.getReturnRate(leveal);
            muser.setMaxMiduoduoRate(str);
        }
        return JsonResp.ok(account);
    }

    /**
     * @param userId
     * @return
     * @查找某一用户的团队
     */
    @RequestMapping(value = "/selectTeamListByUserId", method = RequestMethod.GET)
    public JsonResp selectTeamListByUserId(String userId, Page page) {
        log.debug("查找某一用户的团队");
        if (StringUtil.isEmpty(userId))
            return JsonResp.toFail("用户名不能为空");
//        List<Muser> muserList=muserService.selectTeamListByUserId(userId);
        Map map = new HashMap();
        EntityWrapper<Account> aew = new EntityWrapper<>();
        aew.eq("muser_id", userId);
        Account accc = accountService.selectOne(aew);
        map.put("income", accc.getIncome());//总收益
        map.put("mNumber", muserService.findUserTotalTeamSize(Long.valueOf(userId)));//总人数
        EntityWrapper<Muser> ew = new EntityWrapper<>();

        /*用substring_index(str,delim,count)函数匹配id获取直属团队，delim表示分隔符*/
//        ew.where("SUBSTRING_INDEX(m.recommend_user_ids, ',', 1) = {0} ",userId);
        ew.where("SUBSTRING_INDEX(muser.recommend_user_ids, ',', 1)={0}", userId);
        ew.isNotNull("user_name");

        Page<Muser> teamPage = muserService.selectPage(page, ew);

        List<Muser> musers = teamPage.getRecords();

        for (Muser muser : musers) {
            EntityWrapper<Account> accountEntityWrapper = new EntityWrapper<>();
            accountEntityWrapper.eq("muser_id", muser.getId());
            Account acc = accountService.selectOne(accountEntityWrapper);
            muser.setTotalMoney(acc.getTotalMoney());//总消费
            muser.setIncome(acc.getIncome());//总收益
            muser.setmNumber(muserService.findUserTotalTeamSize(muser.getId()));//总人数
        }
        map.put("teamPage", teamPage);
        return JsonResp.ok(map);

    }


    /**
     * @param userId
     * @return
     * @查找会员所有下级成员
     */
    @RequestMapping(value = "/selectUserTeamList", method = RequestMethod.GET)
    public JsonResp selectUserTeamList(Long userId, Page page) {
        log.debug("查找会员所有下级成员");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.where("SUBSTRING_INDEX(muser.recommend_user_ids, ',', 1)={0}", userId);
        Map map = new HashMap();
        Integer startIndex = (page.getCurrent() - 1) * page.getSize();
        map.put("startIndex", startIndex);
        map.put("size", page.getSize());
        map.put("userId", userId);
        List<Account> accountList = accountService.selectUserTeamList(map);
        Integer num = accountService.selectUserTeamListSize(map);
        for (Account account : accountList) {
            Muser muser = account.getMuser();
            muser.setmNumber(muserService.findUserTotalTeamSize(muser.getId()));
            Integer buyCount = 0;
            if (null != muserService.selectPurchaseFrequencyByUserId(muser.getId())) {
                buyCount = muserService.selectPurchaseFrequencyByUserId(muser.getId());
            }
            muser.setPurchaseFrequency(buyCount);
        }
        page.setRecords(accountList);
        page.setTotal(num);
        return JsonResp.dataPage(page);

    }


    public static void main(String[] args) throws IOException, ParseException, ParseException {
        // 0. Specify the analyzer for tokenizing text.
        //    The same analyzer should be used for indexing and searching
        Analyzer analyzer = new StandardAnalyzer();

        // 1. create the index  内存存储
//        Directory index = new RAMDirectory();
                /**//* *//*  指明要索引文件夹的位置,这里是C盘的S文件夹下 */
        File fileDir = new File(" c:\\s ");
        /**//* *//*  这里放索引文件的位置  */
        File indexDir = new File(" c:\\index ");
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        Boolean createOrAppend = true;//始终重建索引/不存在则追加索引
        if (createOrAppend) {
            indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
        } else {
            indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
        }

        //索引放在内存中
        Directory directory = new RAMDirectory();
//        File indexDir2 = new File(DISC_URL);
//        //索引目录
//        Directory directory=FSDirectory.open(indexDir2);
        //索引文件的写入。
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        //内容提取，进行索引的存储。
        Document doc = new Document();
        String text = "This is the text to be indexed.";
        doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
        indexWriter.addDocument(doc);
        indexWriter.close();

        // Now search the index:
        DirectoryReader ireader = DirectoryReader.open(directory);
        //创建搜索器
        IndexSearcher isearcher = new IndexSearcher(ireader);
        // Parse a simple query that searches for "text":
        QueryParser parser = new QueryParser("fieldname", analyzer);
        Query query = parser.parse("text");

//        ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
        //   表示返回前面10条
        TopDocs topDocs = isearcher.search(query, 10);
        ScoreDoc[] hits = topDocs.scoreDocs;
        System.out.println("有" + hits.length + "个结果");
        for (ScoreDoc sd : hits) {
            //7、根据Searcher和ScordDoc对象获取具体的Document对象
            //获取这个文档的id
            int docc = sd.doc;
            Document document = isearcher.doc(docc);
            //8、根据Document对象获取需要的值
            System.out.println("【找到】" + document.get("fieldname") + "    " + document.get("text") + " .." + document.get("content"));
        }
        ireader.close();
        directory.close();
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @查询所有的用户列表
     */
    @RequestMapping(value = "/admin/selectUserList", method = RequestMethod.GET)
    @CrossOrigin(maxAge = 3600, origins = "*")
    public JsonResp selectUserList(Page page, String userType, String memberLevel, String phone, String memberType, String startTime, String endTime) {

        Map map = new HashMap<>();
        if (memberType != null && !"".equals(memberType)) {
            map.put("memberType", memberType);
        }
        if (memberLevel != null && !"".equals(memberLevel)) {
            map.put("memberLevel", memberLevel);
        }
        if (userType != null && !"".equals(userType)) {
            map.put("userType", userType);
        }
        if (phone != null && !"".equals(phone.trim())) {
            //为数字则查询电话号码，否则查询姓名
            if (phone.matches("^[0-9]*$")) {
                map.put("phone", phone);
            } else {
                map.put("userName", phone);
            }
        }

        if (startTime != null && !"".equals(startTime)) {
            map.put("startTime", startTime);
        }
        if (endTime != null && !"".equals(endTime)) {
            map.put("endTime", endTime);
        }
        Integer startIndex = (page.getCurrent() - 1) * page.getSize();
        map.put("startIndex", startIndex);
        map.put("size", page.getSize());
        List<Account> accountList = accountService.selectAllAccountAndUser(map);
        for (Account account : accountList) {
            Muser muser = account.getMuser();
            muser.setmNumber(muserService.findUserTotalTeamSize(muser.getId()));
            Integer buyCount = 0;
            if (null != muserService.selectPurchaseFrequencyByUserId(muser.getId())) {
                buyCount = muserService.selectPurchaseFrequencyByUserId(muser.getId());
            }
            muser.setPurchaseFrequency(buyCount);
        }
        Integer account = accountService.selectAccountAndUserNums(map);

        page.setRecords(accountList);
        page.setTotal(account);

 /*       Page<Muser> userPage = muserService.selectPage(page, userEntityWrapper);

        List<Muser> musers = userPage.getRecords();

        for (Muser muser : musers) {
            EntityWrapper<Account> accountEntityWrapper = new EntityWrapper<>();
            accountEntityWrapper.eq("muser_id", muser.getId());
            muser.setmNumbser(muserService.findUserTotalTeamSize(muser.getId()));
        }*/

        return JsonResp.dataPage(page);


    }

    /**
     * 计算购买率、复购率等
     *
     * @return
     */
    @RequestMapping(value = "/calcuPurchaseFrequency", method = RequestMethod.GET)
    public JsonResp calcuPurchaseFrequency() {
        log.debug("计算购买率、复购率等");
        Integer geOne = 0;//购买次数大于0人数
        Integer geTwo = 0;//购买次数大于1人数
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.isNotNull("user_name");
        Integer all = muserService.selectCount(ew);
        Map map = new HashMap();
        geOne = muserService.selectPurchaseFrequencyGEANumber(map) == null ? 0 : muserService.selectPurchaseFrequencyGEANumber(map);
        map.put("threshold", 2);
        geTwo = muserService.selectPurchaseFrequencyGEANumber(map) == null ? 0 : muserService.selectPurchaseFrequencyGEANumber(map);
        Double geOneRate = 0d;
        Double geTwoRate = 0d;
        if (all > 0) {
            geOneRate = Double.valueOf(geOne) / Double.valueOf(all);
            if (geOne > 0) {
                geTwoRate = Double.valueOf(geTwo) / Double.valueOf(geOne);
            }
        }
        Map result = new ConcurrentHashMap();
        result.put("geOne", geOne);
        result.put("geTwo", geTwo);
        result.put("geOneRate", geOneRate);
        result.put("geTwoRate", geTwoRate);
        return JsonResp.ok(result);
    }


    /**
     * 会员列表（后台变更上级使用）
     *
     * @param
     * @return 返回值JsonResp
     * @查询所有的用户列表
     */
    @RequestMapping(value = "/selectUsers", method = RequestMethod.GET)
    public JsonResp selectUsers(Page page, String userType, String phone, String memberType, String startTime, String endTime) {
        Map map = new HashMap<>();
        if (memberType != null && !"".equals(memberType)) {
            map.put("memberType", memberType);
        }
        if (userType != null && !"".equals(userType)) {
            map.put("userType", userType);
        }
        if (phone != null && !"".equals(phone.trim())) {
            //为数字则查询电话号码，否则查询姓名
            if (phone.matches("^[0-9]*$")) {
                map.put("phone", phone);
            } else {
                map.put("userName", phone);
            }
        }
        if (startTime != null && !"".equals(startTime)) {
            map.put("startTime", startTime);
        }
        if (endTime != null && !"".equals(endTime)) {
            map.put("endTime", endTime);
        }
        Integer startIndex = (page.getCurrent() - 1) * page.getSize();
        map.put("startIndex", startIndex);
        map.put("size", page.getSize());

        List<Account> accountList = accountService.selectAllAccountAndUser(map);

        for (int i = 0, y = accountList.size(); i < y; i++) {
            Account account = accountList.get(i);
            Muser muser = account.getMuser();
            String recomendUserName = null;
            if (cacheUtil.hasKey("recomendUser" + muser.getId())) {
                recomendUserName = cacheUtil.getString("recomendUser" + muser.getId());
            }
            if (StringUtil.isNotEmpty(recomendUserName)) {
                muser.setParsentUserName(recomendUserName);
            }
        }
        Integer account = accountService.selectAccountAndUserNums(map);
        page.setRecords(accountList);
        page.setTotal(account);
        return JsonResp.dataPage(page);
    }

    /**
     * 删除会员
     * userId 会员id
     * password 后台登录密码
     *
     * @return
     */
    @RequestMapping(value = "/delMuser", method = RequestMethod.GET)
    public JsonResp delMuser(Long userId, String password) {
        Muser muserOld = muserService.selectById(userId);
        EntityWrapper<Admin> ewAdmin = new EntityWrapper<>();
        ewAdmin.eq("password", Md5.md5Encode(password));
        List<Admin> admins = adminService.selectList(ewAdmin);
        if (admins.isEmpty()) {
            return JsonResp.fa("密码不正确");
        }
        //查询关系链中包含该会员id的所有会员列表
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.where(" LOCATE(" + muserOld.getId() + ",muser.recommend_user_ids)>0", "muser.recommend_user_ids");
        List<Muser> musers = muserService.selectList(ew);
        if (!musers.isEmpty()) {
            for (Muser muser : musers) {
                String recommendIds = muser.getRecommendUserIds();
/*                if (recommendIds.contains(muserOld.getId() + ",")) {
                    recommendIds = recommendIds.replace(muserOld.getId() + ",", "");
                } else if (recommendIds.contains(muserOld.getId() + "")) {
                    recommendIds = recommendIds.replace("," + muserOld.getId(), "");
                }*/
                //转成recid的list
                String[] rec = recommendIds.split(",");
                List<String> recIds = Arrays.asList(rec);
                //移除用户id
                recIds.remove(String.valueOf(userId));
                StringBuilder sb = new StringBuilder();
                recIds.forEach(e -> sb.append(",").append(e));
                String recStr = sb.toString().substring(1);
                muser.setRecommendUserIds(recStr);
            }
            muserService.updateBatchById(musers);
        }
        muserService.deleteById(userId);
        return JsonResp.ok("", "删除成功");
    }


    @RequestMapping(value = "/chengeType1", method = RequestMethod.GET)
    public JsonResp chengeType1(long id, int memberType1) {
        Muser muser = muserService.selectById(id);
        muser.setMemberType(memberType1);
        Boolean bool = muserService.updateById(muser);
        return JsonResp.ok(bool);
    }


    @RequestMapping(value = "/chengeType2", method = RequestMethod.GET)
    public JsonResp chengeType2(long id, int userType1) {
        Muser muser = new Muser();
        muser.setId(id);
        muser.setUserType(userType1);
        Boolean bool = muserService.updateById(muser);

        /******* 身份升级成功提示消息******/
        if ((userType1 == UserTypeEnum.CENTURION.getType() || userType1 == UserTypeEnum.ChIEFCOMMANDER.getType()) && bool) {

            Message msg=messageService.selectTemplateMsgByMsgType(3);
            if(null!=msg){
                String title=msg.getTitle();
                String userTypeName = "百夫长";
                if (userType1 == 5) {
                    userTypeName = "千夫长";
                }
                String content=msg.getContent()
                        .replace("#userTypeName#",userTypeName);
                MsgUser msgUser = new MsgUser();
                msgUser.setMuserId(id);
                msgUser.setTitle(title);
                //恭喜你升级成为【#userTypeName#】！
                msgUser.setMsgContent(content);
                msgUserService.insert(msgUser);
            }
        }
        /******* 身份升级成功提示消息******/

        return JsonResp.ok(bool);
    }

    @RequestMapping(value = "/chengeType3", method = RequestMethod.GET)
    public JsonResp chengeType3(long id, int memberLevel1) {
        Muser muser = muserService.selectById(id);
        muser.setMemberLevel(memberLevel1);
        Boolean bool = muserService.updateById(muser);
        return JsonResp.ok(bool);
    }

    @RequestMapping(value = "/disableOrEnable", method = RequestMethod.GET)
    public JsonResp disableOrEnable(Long id) {
        Muser muser = muserService.selectById(id);
        if (muser.getmStatus() == 1) {
            muser.setmStatus(2);
        } else {
            muser.setmStatus(1);
        }
        Boolean bool = muserService.updateById(muser);
        return JsonResp.ok(bool);

    }

    /**
     * 会员添加上级
     *
     * @param userId   会员id
     * @param recomend 上级名称或电话
     * @return
     */
    @RequestMapping(value = "/addRecomendUser", method = RequestMethod.GET)
    public JsonResp addRecomendUser(Long userId, String recomend) {
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        if (MobileUtil.isPhoneBase(recomend)) {
            ew.eq("phone", recomend);
        } else {
            ew.eq("user_name", recomend.trim());
        }
        Muser recomendUser = muserService.selectOne(ew);
        if (recomendUser == null) {
            return JsonResp.fa("该推荐人不存在");
        }
        Muser muser = muserService.selectById(userId);
//        if (StringUtil.isNotEmpty(muser.getRecommendUserIds())) {
//            return JsonResp.fa("该会员已存在推荐人，是否要更新？");
//        }
        //将其推荐人放入缓存中
        if (cacheUtil.hasKey("recomendUser" + userId)) {
            cacheUtil.delkey("recomendUser" + userId);
        }
        cacheUtil.put("recomendUser" + userId, recomendUser.getUserName());
        String recomendIds = StringUtil.isEmpty(recomendUser.getRecommendUserIds()) == true ? recomendUser.getId() + "" : recomendUser.getId() + "," + recomendUser.getRecommendUserIds();
        muser.setRecommendUserIds(recomendIds);
        Boolean bool = muserService.updateById(muser);
        return JsonResp.ok(bool);

    }

    /**
     * 发放注册优惠券
     *
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/releaseRegisterCoupon", method = RequestMethod.GET)
    public JsonResp releaseRegisterCoupon(Long muserId) {
        log.debug("发放注册优惠券");
//        CouponUser cu =
        EntityWrapper<Coupon> ew = new EntityWrapper<>();
        //diff_tag为2表示注册优惠券
        ew.eq("diff_tag", 2);
        List<Coupon> coupons = couponService.selectList(ew);
        if (coupons.size() == 0) {
            return JsonResp.ok("后台暂未配置注册优惠券");
        }
        //优惠券来源 1 常规 2 注册所得 3 分享邀请他人注册下载所得 4 分享到朋友圈后
        Integer source = 2;
        List<CouponUser> couponUsers = new ArrayList<>();
        for (Coupon c : coupons) {
            couponUsers = couponUserService.releaseCouponsForMuser(muserId, coupons, source);
        }
        couponUserService.insertBatch(couponUsers);
        return JsonResp.ok(couponUsers);
    }

    /**
     * 获取某年月彩虹会员列表发放礼品，注册或升级时间、倒序，未发礼品靠前
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/getRainbowMemberListViaPeriod", method = RequestMethod.POST)
    public JsonResp getRainbowMemberListViaPeriod(@RequestBody Page<Muser> page) {
        log.debug("获取某年月彩虹会员列表发放礼品，注册或升级时间、倒序，未发礼品靠前");
        EntityWrapper<Muser> ew = new EntityWrapper<>();
        ew.eq("member_type", 2);
        String queryDate = page.getCondition().get("queryDate").toString();
        if (StringUtil.isNotEmpty(queryDate)) {
            queryDate += "-1";
            String monthWhere = " DATE_FORMAT(\'" + queryDate + "\' , '%Y%m')=DATE_FORMAT(gmt_datetime, '%Y%m' )";
            ew.where(monthWhere);
        }
        String search = page.getCondition().get("searchText").toString();
        if (StringUtil.isNotEmpty(search)) {
            if (search.matches("^[0-9]*$")) {
                ew.like("phone", search);
            } else {
                ew.like("user_name", search);
            }
        }
        String isGifted = page.getCondition().get("isGifted").toString();
        if (StringUtil.isNotEmpty(isGifted)) {
            ew.eq("is_gifted", isGifted);
        }
        ew.orderBy("is_gifted");
        ew.orderBy("gmt_datetime", false);
        page.setCondition(null);
        page = muserService.selectPage(page, ew);
        return JsonResp.ok(page);
    }


}
